package com.youcheng.configcenter.factory;

import com.youcheng.configcenter.convertor.JsonResourceConvertor;
import com.youcheng.configcenter.convertor.PropertiesResourceConvertor;
import com.youcheng.configcenter.convertor.ResourceConvertor;
import com.youcheng.configcenter.convertor.YamlResourceConvertor;
import org.springframework.util.StringUtils;

/**
 * @author sunhongmin
 * @date 2022/10/23 14:42
 * @description
 */
public class ResourceConvertorFactory {

    private static final String PROPERTIES_EXTENSION = ".properties";
    private static final String JSON_EXTENSION = ".json";
    private static final String[] YAML_EXTENSION = {".yml", ".yaml"};


    public static ResourceConvertor getResourceConvertorInstance(String fileName) {
        if (fileName.contains(PROPERTIES_EXTENSION)) {
            return new PropertiesResourceConvertor();
        } else if (fileName.contains(JSON_EXTENSION)) {
            return new JsonResourceConvertor();
        } else if (ResourceConvertorFactory.fileIsYaml(fileName)) {
            return new YamlResourceConvertor();
        } else {
            throw new RuntimeException("配置中心：暂不支持的文件解析类型，fileName:" + fileName);
        }
    }

    private static boolean fileIsYaml(String fileName) {
        for (String extension : YAML_EXTENSION) {
            if (StringUtils.hasLength(fileName) && fileName.contains(extension)) {
                return true;
            }
        }
        return false;
    }

}
